<template>
  <div class="blog-setting-container">
    <el-form
      :model="blogForm"
      :rules="rules"
      ref="blogForm"
      label-width="120px"
      class="demo-ruleForm"
    >
      <div class="form-section">
        
        <el-form-item label="博客名称" prop="blogName">
          <el-input v-model="blogForm.blogName" placeholder="请输入博客名称"></el-input>
        </el-form-item>

        <el-form-item label="作者名字" prop="author">
          <el-input v-model="blogForm.author" placeholder="请输入作者名字"></el-input>
        </el-form-item>

        <el-form-item label="作者头像">
          <el-upload
            class="avatar-uploader"
            action="/admin/upload/avatar"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="el-form-item__error" v-if="avatarError">{{ avatarError }}</p>
        </el-form-item>

        <el-form-item label="介绍语" prop="introduction">
          <el-input 
            type="textarea" 
            v-model="blogForm.introduction" 
            placeholder="请输入博客介绍语"
            rows="3"
          ></el-input>
        </el-form-item>
      </div>

      <!-- 社交平台地址（每个带独立开关） -->
      <div class="form-section">
    
        
        <!-- GitHub -->
        <el-form-item label="GitHub地址" prop="githubHome">
          <div class="url-with-switch">
            <el-switch
              v-model="showGithub"
              class="url-switch"
            ></el-switch>
            <el-input 
              v-show="showGithub"
              v-model="blogForm.githubHome" 
              placeholder="请输入GitHub主页URL"
              style="width: calc(100% - 120px)"
            ></el-input>
          </div>
        </el-form-item>

        <!-- CSDN -->
        <el-form-item label="CSDN地址" prop="csdnHome">
          <div class="url-with-switch">
            <el-switch
              v-model="showCsdn"
            
              class="url-switch"
            ></el-switch>
            <el-input 
              v-show="showCsdn"
              v-model="blogForm.csdnHome" 
              placeholder="请输入CSDN主页URL"
              style="width: calc(100% - 120px)"
            ></el-input>
          </div>
        </el-form-item>

        <!-- Gitee -->
        <el-form-item label="Gitee地址" prop="giteeHome">
          <div class="url-with-switch">
            <el-switch
              v-model="showGitee"
              class="url-switch"
            ></el-switch>
            <el-input 
              v-show="showGitee"
              v-model="blogForm.giteeHome" 
              placeholder="请输入Gitee主页URL"
              style="width: calc(100% - 120px)"
            ></el-input>
          </div>
        </el-form-item>

        <!-- 知乎 -->
        <el-form-item label="知乎地址" prop="zhihuHome">
          <div class="url-with-switch">
            <el-switch
              v-model="showZhihu"
              class="url-switch"
            ></el-switch>
            <el-input 
              v-show="showZhihu"
              v-model="blogForm.zhihuHome" 
              placeholder="请输入知乎主页URL"
              style="width: calc(100% - 120px)"
            ></el-input>
          </div>
        </el-form-item>
      </div>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('blogForm')">保存设置</el-button>
        <el-button @click="resetForm('blogForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    // URL格式验证
    const validateUrl = (rule, value, callback) => {
      // 只有当开关打开且有值时才验证
      const platform = rule.field; // 获取当前字段（如githubHome）
      const showKey = 'show' + platform.charAt(0).toUpperCase() + platform.slice(1, -4); // 对应开关变量（如showGithub）
      
      if (this[showKey] && value && value.trim() !== '') {
        const urlReg = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w.-]*)*\/?$/;
        if (!urlReg.test(value)) {
          return callback(new Error('请输入有效的URL（如：https://github.com）'));
        }
      }
      callback();
    };

    return {
      // 每个平台独立的显示/隐藏开关（默认隐藏）
      showGithub: false,
      showCsdn: false,
      showGitee: false,
      showZhihu: false,

      // 头像相关
      imageUrl: '',
      avatarError: '',

      // 表单数据
      blogForm: {
        blogName: '',
        author: '',
        avatar: '',
        introduction: '',
        githubHome: '',
        csdnHome: '',
        giteeHome: '',
        zhihuHome: ''
      },

      // 验证规则（开关打开时才验证URL）
      rules: {
        blogName: [
          { required: true, message: "请输入博客名称", trigger: "blur" },
          { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
        ],
        author: [
          { required: true, message: "请输入作者名字", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        introduction: [
          { required: true, message: "请输入介绍语", trigger: "blur" },
          { min: 5, max: 500, message: "长度在 5 到 500 个字符", trigger: "blur" }
        ],
        githubHome: [
          { validator: validateUrl, trigger: "blur" }
        ],
        csdnHome: [
          { validator: validateUrl, trigger: "blur" }
        ],
        giteeHome: [
          { validator: validateUrl, trigger: "blur" }
        ],
        zhihuHome: [
          { validator: validateUrl, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 头像上传成功回调
    handleAvatarSuccess(res) {
      this.avatarError = '';
      if (res.success && res.data?.url) {
        this.imageUrl = res.data.url;
        this.blogForm.avatar = res.data.url;
      } else {
        this.avatarError = res.message || "头像上传失败，请重试";
      }
    },
    // 上传前校验
    beforeAvatarUpload(file) {
      this.avatarError = '';
      const isImg = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImg) {
        this.avatarError = '上传文件必须是图片格式';
        return false;
      }
      if (!isLt2M) {
        this.avatarError = '上传图片大小不能超过 2MB';
        return false;
      }
      return true;
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/admin/blog/setting/update', this.blogForm)
            .then(res => {
              if (res.data.success) {
                this.$message.success('保存成功！');
              } else {
                this.$message.error(res.data.message || '保存失败');
              }
            })
            .catch(err => {
              this.$message.error('请求失败：' + (err.message || '网络异常'));
            });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.imageUrl = '';
      this.blogForm.avatar = '';
      this.avatarError = '';
      this.showGithub = false;
      this.showCsdn = false;
      this.showGitee = false;
      this.showZhihu = false;
    }
  }
};
</script>

<style scoped>
.blog-setting-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
}

.form-section {
  padding: 15px 0;
  border-bottom: 1px dashed #f0f0f0;
}

.form-section:last-of-type {
  border-bottom: none;
}

.section-title {
  margin: 0 0 15px;
  font-size: 16px;
  color: #1f2329;
  font-weight: 500;
}
.url-with-switch {
  display: flex;
  align-items: center;
  gap: 10px;
}

.url-switch {
  width: 110px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 6px;
}

.el-form-item__error {
  margin-top: 5px;
}
</style>